package pers.zero.jwt.spring;

import pers.zero.jwt.entity.UserPrinciple;
import pers.zero.jwt.util.JwtClientUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * <p><b>
 * 当前线程 用户信息管理 对象
 * </b></p>
 * <br/>
 * 创建时间: 9/3/2019 11:34 AM
 *
 * @author Zero
 */
public class UserPrincipleManager {

    /**
     * <br/>
     */
    private static final ThreadLocal<UserPrinciple> THREAD_LOCAL =
            new ThreadLocal<>();

    private static String TOKEN_HEADER = "Authorization";


    public static UserPrinciple setUserPrinciple(HttpServletRequest request) {

        String header = request.getHeader(TOKEN_HEADER);
        // 校验 token 是否为空
        if (header == null || "".equalsIgnoreCase(header.trim())) {
            return null;
        }

        UserPrinciple principle = JwtClientUtil.decodeToken(header);

        if (principle != null) {
            THREAD_LOCAL.set(principle);
        }

        return principle;

    }

    /**
     * 获取 当前请求线程 用户信息
     *
     * @return info
     */
    public static UserPrinciple getPrinciple() {
        return THREAD_LOCAL.get();
    }

    /**
     * <b>不要调用此方法</b>
     * 在缓存中移除 用户信息，调用此方法后无法再 获取到用户信息！<br/>
     */
    public static void removeUserPrinciple() {
        THREAD_LOCAL.remove();
    }


    /**
     * 获取 更新后 对象 (主要是时间戳)
     *
     * @return updated UserPrinciple
     */
    public static UserPrinciple getUpdatePrinciple() {
        UserPrinciple principle = getPrinciple();

        if (principle == null) {
            return null;
        }

        principle.setTimestamp(System.currentTimeMillis());
        return principle;
    }
}
